package com.cnnp.dip.business.common.util;

import java.lang.reflect.Field;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanUtil {

    private static final Logger log = LoggerFactory.getLogger(BeanUtil.class);

    /**
     * 将Map中的数据复制到目标对象的字段中
     *
     * @param source Map数据源
     * @param target 目标对象
     */
    public static void copyProperties(Map<String, Object> source, Object target) {
        if (source == null || target == null) {
            return;
        }

        Class<?> targetClass = target.getClass();
        for (Map.Entry<String, Object> entry : source.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                try {
                    Field field = targetClass.getDeclaredField(fieldName);
                    field.setAccessible(true);

                    // 类型转换
                    if (field.getType() == String.class && !(value instanceof String)) {
                        value = value.toString();
                    }

                    field.set(target, value);

                    log.info("Copying field {} with value {} to {}", fieldName, value, targetClass.getSimpleName());
                } catch (NoSuchFieldException e) {
                    log.warn("Field {} not found in {}", fieldName, targetClass.getSimpleName());
                } catch (IllegalAccessException e) {
                    log.warn("Failed to set field {} in {}", fieldName, targetClass.getSimpleName(), e);
                }
            }
        }
    }
} 